
%
% Assumes that groups.dat has the neural area data.
% Assumes you are in the voltages directory.
% Assumes you ran the merge program to merge across processors, or ran on 1
% proc.
% File format for voltages/*.dat file: T lines with the following format:
% neuron# d1 d2 ... dM d1 d2 ... dM ... (repeated N times, N=# neurons in area)
%
% Assumes that d1 is always the neuron #.  
%
% function displayMovie(area_name, type_name, surface, data_columns,
%     data_columns_per_neuron, limits, write_avi_movie)
% displayMovieAreaDump('M1', 'p23', false, 5,8 );
% displayMovieAreaDump('M1', 'p23', false, [5 6],8, [mindataval maxdataval]);
% displayMovieAreaDump('M1', 'p23', false, 5,8, [mindataval maxdataval], false);
%
% datacolumns can be up to 2.
% 
function displayMovieAreaDump(area_name, type_name, surface, data_columns, data_columns_per_neuron, limits, write_avi_movie)

global a b

%disp('Did you run scripttomergeprocs?');

if ~exist('surface')
	surface = false
end
if ~exist('write_avi_movie')
	write_avi_movie = false
end

cd ..
read_groups; % Assumes groups.dat has the neural area data
cd voltages

index = [];
for i=1:length(areas)
    if strcmp( deblank(areas{i}), area_name) && strcmp( type_name, deblank(celltype{i})) 
        index = i
        break;
    end
end
if isempty(index)
    disp([area_name ' ' type_name ' is not in groups.dat.']);
    return;
end

rows = la(index);
cols = lb(index);


filename = [area_name type_name '-0.dat'];
a = load(filename);


if length(data_columns) > 1
    b=[ a(1,1:data_columns_per_neuron:end);a(:,data_columns(2):data_columns_per_neuron:end)]';
    b=sortrows(b,1);
    b=b(:,2:end)';
end

a=[ a(1,1:data_columns_per_neuron:end);a(:,data_columns(1):data_columns_per_neuron:end)]';
a=sortrows(a,1);
a=a(:,2:end)';




fig=figure;
set(fig,'DoubleBuffer','on');

if write_avi_movie 
	mov = avifile('network.avi')
end

if ~exist('limits')
    low=min(min(a));
    hi=max(max(a));
else 
    low = limits(1);
    hi= limits(2);
end




for i=1:size(a,1)
    
    %set(gca,'nextplot','replacechildren');
    if length(data_columns) > 1
        subplot(1,2,1);
    end
    if surface
        surf( reshape( a(i,:) , rows, cols ) ); view([70 6]); axis on;
    else
        imagesc( rot90(reshape( a(i,:) , rows, cols )) ,[low hi]);  colormap(gray);    axis off
    end
    
    title( [area_name type_name ' ' num2str(i)] );

    if length(data_columns) > 1
        subplot(1,2,2);
        if surface
            surf( reshape( b(i,:) , rows, cols ) ); view([70 6]); axis on;
        else
            imagesc( rot90(reshape( b(i,:) , rows, cols )) ,[low hi]);  colormap(gray);    axis off
        end
    end
        
    drawnow;
    %pause(.5);
    
    if write_avi_movie
        F = getframe(gcf);
        mov = addframe(mov,F);
    end
end

if write_avi_movie
	mov = close(mov);
end